package common

import (
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

var JwSecret = []byte("cloud_random_key")

// 过期时间设置为一个月
var ExpireTime = time.Hour * 24 * 30

type Claims struct {
	Username string   `json:"username"`
	Sub      string   `json:"sub"` // 可扩展权限字段
	Roles    []string `json:"roles"`
	jwt.RegisteredClaims
}

func GenerateToken(userId string, username string) (string, error) {
	claims := &Claims{
		Username: username,
		Sub:      userId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(ExpireTime)),
			Issuer:    "ssr",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(JwSecret)
}

func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return JwSecret, nil
	})
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

func GetCurrentUserID(c *gin.Context) string {
	// 从Authorization头获取token
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" {
		return ""
	}

	// 检查Bearer token格式
	tokenString := strings.TrimPrefix(authHeader, "Bearer ")
	if tokenString == authHeader {
		return "" // 没有Bearer前缀
	}

	// 解析token
	claims, err := ParseToken(tokenString)
	if err != nil {
		return ""
	}

	return claims.Sub
}

// GetExpirationTime 获取过期时间
func GetExpirationTime(hours int64) *jwt.NumericDate {
	return jwt.NewNumericDate(time.Now().Add(time.Duration(hours) * time.Hour))
}

// GetCurrentTime 获取当前时间
func GetCurrentTime() time.Time {
	return time.Now()
}
